<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        table {
            border-collapse: collapse;
        }
        td {
            border: 1px solid #ccc;
            padding: 10px;
            text-align: center;
        }
        .highlight {
            background-color: yellow;
        }
        .grayed-out {
            color: #ccc;
        }

        .signed {
            background-color: blue; /* 蓝色背景色 */
            color: white; /* 白色文字颜色，以便文字能够清晰显示在蓝色背景上 */
        }

        #calendarContainer {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh; /* 设置父容器的高度为视口高度 */
        }

        #calendarContainer > div {
            display: flex;
            align-items: center;
            margin-bottom: 10px; /* 调整按钮和月份之间的间距 */
        }

        #signInBtn {
            margin-right: 50px; /* 调整按钮和月份之间的间距 */
        }
    </style>
</head>
<body>
<div id="calendarContainer">
    <div>
        <button id="signInBtn">签到</button>
        <span id="currentMonth" style="color: cornflowerblue"></span>
    </div>
    <p id="signCount"></p>
    <table id="calendarTable">
        <thead>
        <tr>
            <th>周一</th>
            <th>周二</th>
            <th>周三</th>
            <th>周四</th>
            <th>周五</th>
            <th>周六</th>
            <th>周日</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>


<script>
    // 获取当前日期信息
    const currentDate = new Date();
    let currentYear = currentDate.getFullYear();
    let currentMonth = currentDate.getMonth();

    // 获取显示月份的 DOM 元素
    const currentMonthElement = document.getElementById('currentMonth');

    // 获取表格和相关按钮的 DOM 元素
    const calendarTable = document.getElementById('calendarTable');

    // 更新日历显示
    function updateCalendar() {
        // 清空原有表格内容
        while (calendarTable.tBodies[0].firstChild) {
            calendarTable.tBodies[0].removeChild(calendarTable.tBodies[0].firstChild);
        }

        // 更新显示月份
        currentMonthElement.textContent = `${currentYear}年${currentMonth + 1}月`;

        // 生成新的日历数据
        const firstDay = new Date(currentYear, currentMonth, 1).getDay();
        const totalDays = new Date(currentYear, currentMonth + 1, 0).getDate();

        let currentRow = calendarTable.tBodies[0].insertRow();
        let currentCellIndex = 0;

        for (let i = 1; i <= totalDays; i++) {
            // 创建新的单元格
            const cell = currentRow.insertCell();
            cell.textContent = i;

            // 设置样式和签到状态
            const currentDateObj = new Date(currentYear, currentMonth, i);
            if (currentDateObj > currentDate) {
                cell.classList.add('grayed-out');
            } else if (currentDateObj.toDateString() === currentDate.toDateString()) {
                // cell.classList.add('highlight');
                // cell.dataset.signed = 'false'; // 取消当天默认为签到状态
                // cell.addEventListener('click', toggleSign);
            }

            // 判断是否需要创建新的行
            currentCellIndex++;
            if (currentCellIndex >= 7) {
                currentRow = calendarTable.tBodies[0].insertRow();
                currentCellIndex = 0;
            }

        }
    }

    // 初始化日历显示
    updateCalendar();


    // 获取签到按钮的 DOM 元素
    const signInBtn = document.getElementById('signInBtn');

    // 监听签到按钮点击事件
    signInBtn.addEventListener('click', signIn);

    // 签到函数
    function signIn() {
        const currentDateCell = getCurrentDateCell();

        if (currentDateCell) {
            const isSigned = currentDateCell.dataset.signed === 'true';

            if (!isSigned) {
                // 发送签到的请求
                const xhr = new XMLHttpRequest();
                xhr.open('GET', 'http://member.travel.com/member/sign');
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === XMLHttpRequest.DONE) {
                        if (xhr.status === 200) {
                            const result = JSON.parse(xhr.responseText);
                        } else {
                            console.error('签到失败');
                        }
                    }
                };
                xhr.send();

                currentDateCell.dataset.signed = 'true';
                currentDateCell.classList.add('highlight');

                // 计算连续签到天数
                const consecutiveDays = calculateConsecutiveDays();
                alert(`连续签到 ${consecutiveDays} 天`);

                // 重新计算连续签到次数
                signCount();
                location.reload();
            } else {
                alert('已经签到了');
            }
        }
    }

    // 获取当前日期的单元格
    function getCurrentDateCell() {
        const currentDateObj = new Date(currentYear, currentMonth, currentDate.getDate());
        const cells = document.querySelectorAll('#calendarTable td');

        for (const cell of cells) {
            const cellDate = new Date(currentYear, currentMonth, Number(cell.textContent));

            if (cellDate.toDateString() === currentDateObj.toDateString()) {
                return cell;
            }
        }

        return null;
    }

    // 计算连续签到天数
    function calculateConsecutiveDays() {
        const cells = document.querySelectorAll('#calendarTable td');
        let consecutiveDays = 0;
        let currentConsecutiveDays = 0;

        for (const cell of cells) {
            if (cell.dataset.signed === 'true') {
                currentConsecutiveDays++;
            } else {
                currentConsecutiveDays = 0;
            }

            if (currentConsecutiveDays > consecutiveDays) {
                consecutiveDays = currentConsecutiveDays;
            }
        }

        return consecutiveDays;
    }


    // 发起 AJAX 请求获取用户签到记录
    function fetchUserSignInRecord() {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://member.travel.com/member/signRecord');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    const result = JSON.parse(xhr.responseText);
                    initCalendar(result);
                } else {
                    console.error('Failed to fetch user sign-in record');
                }
            }
        };
        xhr.send();
    }

    // 初始化日历显示
    function initCalendar(result) {
        // 获取签到记录列表
        const signList = result.signList;

        // 遍历签到记录，获取签到日期和对应的单元格
        for (const sign of signList) {
            const { memberId, time } = sign;
            const signDate = new Date(time);
            const signCell = getSignCell(signDate);

            // 如果找到了对应的单元格，则标记为已签到
            if (signCell) {
                signCell.dataset.signed = 'true';
                // signCell.classList.remove('highlight');
                signCell.classList.add('highlight');
            }
        }
    }

    // 根据日期获取对应的单元格
    function getSignCell(signDate) {
        const cells = document.querySelectorAll('#calendarTable td');

        for (const cell of cells) {
            const cellDate = new Date(currentYear, currentMonth, Number(cell.textContent));

            if (cellDate.toDateString() === signDate.toDateString()) {
                return cell;
            }
        }

        return null;
    }

    // 页面加载完成后执行的函数
    window.onload = function() {
        fetchUserSignInRecord(); // 获取用户签到记录
        signCount(); // 获取并显示连续签到次数
    };

    // 获取本月连续签到次数
    function signCount(){
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://member.travel.com/member/signCount');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    const result = JSON.parse(xhr.responseText);
                    const signCount = result.signCount;
                    // 赋值
                    const signCountElement = document.getElementById('signCount');
                    signCountElement.textContent = `已连续签到${signCount}天`;
                } else {
                    console.error('Failed to fetch user sign-in record');
                }
            }
        };
        xhr.send();
    }
</script>
</body>
</html>